//
//  ARTWatchMonitorController.m
//  ChartsDemo
//
//  Created by 刘权 on 2021/10/11.
//

#import "ARTWatchMonitorController.h"
// controllers
#import "ARTWatchMonitoringController.h"
#import "ARTWatchHistorySleepController.h"
#import "ARTMainTabController.h"
// views
#import "CircleView.h"
#import "ARTWatchHisAlertView.h"
// models
#import "ARTWathDataAnalysis.h"
#import <ChartsDemo-Swift.h>

@interface ARTWatchMonitorController (){
    BOOL _hadAutoGotoSleep;
}

// 空数据view
@property (weak, nonatomic) IBOutlet UIView *noDataView;
@property (weak, nonatomic) IBOutlet UILabel *noDataLabel;
@property (weak, nonatomic) IBOutlet UIImageView *watchImageView;

// 历史数据
@property (weak, nonatomic) IBOutlet UIView *hisDataView;
@property (weak, nonatomic) IBOutlet YYLabel *timeLabel;
@property (weak, nonatomic) IBOutlet UILabel *yangJianLabel;
@property (weak, nonatomic) IBOutlet UIView *yangJianChart;
@property (weak, nonatomic) IBOutlet UILabel *xueYangLabel;
@property (weak, nonatomic) IBOutlet UIView *xueYangChart;
@property (strong, nonatomic)  CircleView *yangJianCircleView;
@property (strong, nonatomic)  CircleView *xueYangCircleView;

// 实时数据
@property (weak, nonatomic) IBOutlet UIImageView *batteryImageView;
@property (weak, nonatomic) IBOutlet UILabel *spoLabel;
@property (weak, nonatomic) IBOutlet UILabel *piLabel;

// 日常监测
@property (weak, nonatomic) IBOutlet UIButton *dailyButton;
// 睡眠监测
@property (weak, nonatomic) IBOutlet UIButton *sleepButton;

@property (strong, nonatomic)  ARTWatchHisAlertView *alertView;
@property (assign, nonatomic)  BOOL  showAlert;

// 连接状态
@property (assign, nonatomic)  BOOL  isConnected;
// 数据接收状态
@property (assign, nonatomic)  BOOL  isReceivedData;

@property (strong, nonatomic)  ARTWathDataAnalysis *dataAnalysis;

@property (strong, nonatomic)  ARTWathDataModel *realDataModel;

@end

@implementation ARTWatchMonitorController

#pragma mark--THE LIFE CYCLE
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    J_Add_Notify(self, @selector(refreshLanguage), ART_Notify_LanguageChanged, nil);
    [self refreshLanguage];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [self.currentPeripheral writeValue:[ARTWathDataAnalysis getDeviceHisAllCount] forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithResponse];
    });
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    // 设置蓝牙代理
    if (!_isReceivedData) {
        self.isReceivedData = NO;
    }
    _isConnected = NO;
    [self babyDelegate];
}

- (void)dealloc{
    J_Remove_Notify(self);
}

- (void)initSubviews{
    [super initSubviews];
    J_ViewRadius(_dailyButton, 5);
    [_dailyButton setBackgroundImage:[UIImage qmui_imageWithColor:J_ColorFromHEX(0x0095B6)] forState:UIControlStateNormal];
    [_dailyButton setBackgroundImage:[UIImage qmui_imageWithColor:J_ColorFromHEX(0xCCCCCC)] forState:UIControlStateDisabled];
    
    J_ViewRadius(_sleepButton, 5);
    [_sleepButton setBackgroundImage:[UIImage qmui_imageWithColor:J_ColorFromHEX(0x0095B6)] forState:UIControlStateNormal];
    [_sleepButton setBackgroundImage:[UIImage qmui_imageWithColor:J_ColorFromHEX(0xCCCCCC)] forState:UIControlStateDisabled];
    
    _alertView = [[ARTWatchHisAlertView alloc]init];
    [_alertView.okButton addTarget:self action:@selector(okAction) forControlEvents:UIControlEventTouchUpInside];
    [_alertView.cancleButton addTarget:self action:@selector(cancleAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_alertView];
    [_alertView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(30);
        make.right.equalTo(self.view).offset(-30);
        make.height.mas_equalTo(100);
        make.bottom.equalTo(_dailyButton.mas_top).offset(-30);
    }];
    _alertView.transform = CGAffineTransformMakeScale(0.0001, 0.0001);
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    CGFloat circle_W = 140;
    if (isIPhoneX) {
        circle_W = kScale_W(150);
    }
    if (!_yangJianCircleView) {
        _yangJianCircleView = [[CircleView alloc] initWithFrame:J_Frame(0, 0, circle_W, circle_W)];//[[CircleView alloc] initWithFrame:J_Frame(0, 0, _yangJianChart.v_w-10, _yangJianChart.v_h-10)];
        _yangJianCircleView.center = CGPointMake(_yangJianChart.v_w/2-10, _yangJianChart.v_h/2);
        _yangJianCircleView.titleLab.text = @"0.0";
        _yangJianCircleView.tipLab.text = [NSString stringWithFormat:@"%@/h",FYLocalizedString(@"times", @"")];
//        _yangJianCircleView.tipLab.hidden = YES;
//        [_yangJianCircleView adjustTitleLabCenter];
        [_yangJianChart addSubview:_yangJianCircleView];
    }
    if (!_xueYangCircleView) {
        _xueYangCircleView = [[CircleView alloc] initWithFrame:_yangJianCircleView.frame];
        _xueYangCircleView.titleLab.text = @"0.0";
        _xueYangCircleView.tipLab.text = @"SpO2%";
//        _xueYangCircleView.tipLab.hidden = YES;
//        [_xueYangCircleView adjustTitleLabCenter];
        [_xueYangChart addSubview:_xueYangCircleView];
    }
    
    // 展示历史睡眠数据
    [self showSleepHistoryData];
}

- (void)syncWithWatchFile{
    if (!_isConnected) {
        [QMUITips showWithText:FYLocalizedString(@"oxygen_off_line", @"")];
        return;
    }
//    if (ARTSingleShare.watchDevHisAllNumber == 0) {
//        [QMUITips showWithText:FYLocalizedString(@"sleep_watch_nodata", @"")];
//        return;
//    }
    if ([self.dataAnalysis syncAllFileList]) {
        [QMUITips showLoading:FYLocalizedString(@"sleep_watch_data_synchronization", @"") inView:[ARTNavigation currentNavigationViewController].view];
        self.dataAnalysis.isSyncFile = YES;
        self.dataAnalysis.call_syncComplete_back = ^(NSArray * _Nullable hisArray) {
            [QMUITips hideAllTips];
            if (hisArray.count == 0) {
                [QMUITips showWithText:FYLocalizedString(@"sleep_watch_nodata", @"")];
            }else{
                J_Post_Notify(ART_Notify_WatchSyncComplete);
            }
        };
    }
}

#pragma mark--PRIVATE METHOD
- (void)refreshLanguage{
    // 空页面展示
    _noDataLabel.text = FYLocalizedString(@"sleep_watch_no_sleep_monitoring", @"");
    
    // 历史数据展示
    _timeLabel.text = @"2021-10-18 时长：20:25:32";
    _yangJianLabel.text = @"氧减饱和度指数:正常";
    _xueYangLabel.text = FYLocalizedString(@"sleep_watch_sp_low", @"");
    
    // 实时
    self.realDataModel = _realDataModel;
    
    [_dailyButton setTitle:FYLocalizedString(@"sleep_watch_daily_test", @"") forState:UIControlStateNormal];
    [_sleepButton setTitle:FYLocalizedString(@"sleep_watch_sleep_test", @"") forState:UIControlStateNormal];
    
    _yangJianCircleView.tipLab.text = [NSString stringWithFormat:@"%@/h",FYLocalizedString(@"second", @"")];
    
    _watchImageView.image = J_ImageNamed(FYLocalizedString(@"sleep_image_watch", @""));
    
    [_alertView refreshLaunage];
}

// 展示历史睡眠数据
- (void)showSleepHistoryData{
    // 判断是否有睡眠历史数据
    NSArray *watchArray = [NSUserDefaults jk_arrayForKey:App_History_SleepWatch];
    if (watchArray.count == 0) {
        _noDataView.hidden = NO;
        _hisDataView.hidden = YES;
    }else{
//        watchArray = [ARTWatchHisModel mj_objectArrayWithKeyValuesArray:watchArray];
        NSString *jsonString = watchArray.firstObject;
        jsonString = [RSAEncryptor decryptSubsectionString:jsonString privateKey:ART_Prikey];
        ARTWatchHisModel *model = [ARTWatchHisModel mj_objectWithKeyValues:jsonString];
        _noDataView.hidden = YES;
        _hisDataView.hidden = NO;
        
        NSString *date = model.date;
        if (date.length > 10) {
            date = [date substringToIndex:10];
        }
        NSMutableAttributedString *textAttribute = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@ ",date] attributes:@{NSFontAttributeName:J_Font(14),NSForegroundColorAttributeName:J_ColorFromHEX(0x999999)}];
        UIImage *image = J_ImageNamed(@"watch_ic_sleep");
        NSAttributedString *attachment = [NSAttributedString attachmentStringWithContent:image contentMode:UIViewContentModeCenter attachmentSize:CGSizeMake(image.size.width+10, image.size.height) alignToFont:J_MediumFont(14) alignment:YYTextVerticalAlignmentCenter];
        [textAttribute appendAttributedString:attachment];
        [textAttribute appendAttributedString:[[NSAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@%@",FYLocalizedString(@"sleep_watch_lasttime", @""),[Tool getMMSSFromSS:model.longTime]] attributes:@{NSFontAttributeName:J_Font(14),NSForegroundColorAttributeName:J_ColorFromHEX(0x999999)}]];
        _timeLabel.numberOfLines = 2;
        _timeLabel.attributedText = textAttribute;
        
//        _timeLabel.text = [NSString stringWithFormat:@"%@%@  %@%@",FYLocalizedString(@"oxygen_time_test", @""),model.date,FYLocalizedString(@"oxygen_time_Long", @""),[Tool getMMSSFromSS:model.longTime]];
        
        NSString *odiTitle = FYLocalizedString(@"oxygen_normal", @"");
        UIColor *odiColor = J_ColorFromHEX(0x0DA462);
        if (model.odi <= 5) {
            odiTitle = FYLocalizedString(@"oxygen_normal", @"");
            odiColor = J_ColorFromHEX(0x0DA462);
        }else if (model.odi <= 15){
            odiTitle = FYLocalizedString(@"oxygen_light", @"");
            odiColor = J_ColorFromHEX(0xFFE84A);
        }else if (model.odi <= 30){
            odiTitle = FYLocalizedString(@"oxygen_moderate", @"");
            odiColor = J_ColorFromHEX(0xFF9627);
        }else{
            odiTitle = FYLocalizedString(@"oxygen_severe", @"");
            odiColor = J_ColorFromHEX(0xE50C0C);
        }
        _yangJianLabel.adjustsFontSizeToFitWidth = YES;
        _yangJianLabel.text = [NSString stringWithFormat:@"%@：%@",FYLocalizedString(@"sleep_watch_knowledge_title2", @""),odiTitle];
        
        NSString *spoTitle = FYLocalizedString(@"oxygen_normal", @"");
        if ((model.spo2_95+model.spo2_90+model.spo2_85)*1.0/model.dataList.count > 0.05) {
            spoTitle = FYLocalizedString(@"oxygen_low", @"");
        }
        _xueYangLabel.adjustsFontSizeToFitWidth = YES;
        _xueYangLabel.text = [NSString stringWithFormat:@"%@：%@",FYLocalizedString(@"sleep_watch_knowledge_title1", @""),spoTitle];
        _yangJianCircleView.titleLab.text = [NSString stringWithFormat:@"%.1f",model.odi];
//        [_yangJianCircleView setPercent:model.odi*1.8 animated:YES];
        [_yangJianCircleView setPercent:model.odi color:odiColor animated:YES];
        _xueYangCircleView.titleLab.text = @(model.spo2Min).stringValue;
        [_xueYangCircleView setPercent:model.spo2Min*1.8 animated:YES];
        
        [_hisDataView whenTapped:^{
            ARTWatchHistorySleepController *controller = [[ARTWatchHistorySleepController alloc]init];
            controller.receiveModel = model;
            [ARTNavigation pushViewController:controller animated:YES];
        }];
    }
}

// 设置蓝牙代理
- (void)babyDelegate{
    _baby = ARTSingleShare.baby;
    _currentPeripheral = ARTSingleShare.currentPeripheral;
    _notifyCharacteristic = ARTSingleShare.currentCharacteristic;
    _writeCharacteristic = ARTSingleShare.writeCharacteristic;
    if (!_baby || !_currentPeripheral || !_notifyCharacteristic || !_writeCharacteristic) {
        return;
    }
    
    J_WeakSelf(self)
    // 监听蓝牙数据
    [_baby notify:_currentPeripheral characteristic:_notifyCharacteristic block:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
        J_StrongSelf(self)
        [self.dataAnalysis analysisData:characteristics.value];
        self.isConnected = YES;
    }];
    
    // 数据写入成功
    [_baby setBlockOnDidWriteValueForCharacteristic:^(CBCharacteristic *characteristic, NSError *error) {
        NSLog(@"====数据写入成功name：%@",characteristic.value);
    }];
        
    // 断开连接
    [self.baby setBlockOnDisconnect:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {
        J_StrongSelf(self)
        self.isReceivedData = NO;
        self.isConnected = NO;
        if (!error) {
            NSLog(@"====手动断开连接设备2name：%@",peripheral.name);
        }else{
            NSLog(@"====自动断开连接设备2name：%@,error:%@",peripheral.name,error);
        }
        if (self.dataAnalysis.isSyncFile) {
            [QMUITips hideAllTips];
            [self.dataAnalysis syncAllComplete];
            [QMUITips showWithText:FYLocalizedString(@"oxygen_off_line", @"")];
        }
    }];
    
//    [self.currentPeripheral writeValue:[ARTWathDataAnalysis syncTimestamp] forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithResponse];
//    [self.currentPeripheral writeValue:[ARTWathDataAnalysis getDeviceHisAllCount] forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithResponse];
    // 安全
    Byte byteData[] = {0xFE,0x5A,0x06,0x1D,1,0};
    [self.currentPeripheral writeValue:[NSData dataWithBytes:byteData length:6] forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithResponse];
    NSLog(@"====安全写入=%@",[NSData dataWithBytes:byteData length:6]);
}

- (void)configureBattery{
    UIImage *image = J_ImageNamed(@"watch_ic_notice0");
    if (_realDataModel) {
        NSString *name = [NSString stringWithFormat:@"watch_ic_notice%@",@(_realDataModel.battery)];
        image = J_ImageNamed(name);
    }
    _batteryImageView.image = image;
}

#pragma mark--TARGET ACTION
- (IBAction)dailyAction:(id)sender {
    [self.currentPeripheral writeValue:[ARTWathDataAnalysis syncMeasuringType:ARTWatchMonitorTypeDaily] forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithResponse];
    [self gotoMonitorController:ARTWatchMonitorTypeDaily];
}

- (IBAction)sleepAction:(id)sender {
    [self.currentPeripheral writeValue:[ARTWathDataAnalysis syncMeasuringType:ARTWatchMonitorTypeSleep] forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithResponse];
    [self gotoMonitorController:ARTWatchMonitorTypeSleep];
}

- (void)gotoMonitorController:(ARTWatchMonitorType)type{
    ARTWatchMonitoringController *controller = [[ARTWatchMonitoringController alloc]init];
    controller.baby = self.baby;
    controller.currentPeripheral = self.currentPeripheral;
    controller.notifyCharacteristic = self.notifyCharacteristic;
    controller.writeCharacteristic = self.writeCharacteristic;
    controller.monitorType = type;
    controller.disConnectBlock = ^{
        self.isReceivedData = NO;
    };
    [ARTNavigation pushViewController:controller animated:YES];
}

- (void)okAction{
    self.showAlert = NO;
    ARTMainTabController *tabVC = (ARTMainTabController *)self.tabBarController;
    tabVC.selectedIndex = 1;
    [tabVC didSelectWithIndex:1];
    [self syncWithWatchFile];
}

- (void)cancleAction{
    self.showAlert = NO;
}

//- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//    [super touchesBegan:touches withEvent:event];
////    [self gotoMonitorController:ARTWatchMonitorTypeDaily];
//    self.showAlert = YES;
//}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark--SETTER
- (void)setIsReceivedData:(BOOL)isReceivedData{
    _isReceivedData = isReceivedData;
    _dailyButton.enabled = _sleepButton.enabled = isReceivedData;
    if (!isReceivedData) {
        self.realDataModel = nil;
    }
}

- (void)setRealDataModel:(ARTWathDataModel *)realDataModel{
    _realDataModel = realDataModel;
    NSString *spo2 = @"--";
    NSString *pr = @"--";
    if (realDataModel.isValid) {
        spo2 = @(realDataModel.spo2).stringValue;
        pr = @(realDataModel.pr).stringValue;
        self.isReceivedData = YES;
    }
    _spoLabel.attributedText = [self attributeTextForRealWithValue:spo2 unit:@"%" message:FYLocalizedString(@"sleep_watch_knowledge_title1", @"")];
    _piLabel.attributedText = [self attributeTextForRealWithValue:pr unit:@"/min" message:FYLocalizedString(@"sleep_watch_pr", @"")];
    [self configureBattery];
    
    // 如果为睡眠数据，直接进入睡眠测量
    if (realDataModel.type == 2 && !_hadAutoGotoSleep) {
        _hadAutoGotoSleep = YES;
        [self gotoMonitorController:ARTWatchMonitorTypeSleep];
    }
}

- (NSAttributedString *)attributeTextForRealWithValue:(NSString *)value unit:(NSString *)unit message:(NSString *)message{
    NSMutableAttributedString *valueAttribute = [[NSMutableAttributedString alloc]initWithString:value attributes:@{NSForegroundColorAttributeName:J_ColorFromHEX(0x222222),NSFontAttributeName:J_MediumFont(32)}];
    NSAttributedString *unitAttribute = [[NSAttributedString alloc]initWithString:unit attributes:@{NSForegroundColorAttributeName:J_ColorFromHEX(0x222222),NSFontAttributeName:J_Font(14)}];
    NSAttributedString *msgAttribute = [[NSAttributedString alloc]initWithString:message attributes:@{NSForegroundColorAttributeName:J_ColorFromHEX(0x666666),NSFontAttributeName:J_Font(12)}];
    
    [valueAttribute appendAttributedString:unitAttribute];
    [valueAttribute appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n" attributes:nil]];
    [valueAttribute appendAttributedString:msgAttribute];
    return valueAttribute;
}

- (void)setShowAlert:(BOOL)showAlert{
    _showAlert = showAlert;
    if (showAlert) {
        [UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:0.69 initialSpringVelocity:5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            self.alertView.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
        }];
    }else{
        [UIView animateWithDuration:0.1 delay:0 usingSpringWithDamping:0.69 initialSpringVelocity:5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            self.alertView.transform = CGAffineTransformMakeScale(0.0001, 0.0001);
        } completion:^(BOOL finished) {
        }];
    }
}

#pragma mark--GETTER
//- (NSArray *)crc_tab {
//    return @[
//        @(0x00000000), @(0x77073096),
//        @(0xEE0E612C), @(0x990951BA), @(0x076DC419), @(0x706AF48F), @(0xE963A535),
//        @(0x9E6495A3), @(0x0EDB8832), @(0x79DCB8A4), @(0xE0D5E91E), @(0x97D2D988),
//        @(0x09B64C2B), @(0x7EB17CBD), @(0xE7B82D07), @(0x90BF1D91), @(0x1DB71064),
//        @(0x6AB020F2), @(0xF3B97148), @(0x84BE41DE), @(0x1ADAD47D), @(0x6DDDE4EB),
//        @(0xF4D4B551), @(0x83D385C7), @(0x136C9856), @(0x646BA8C0), @(0xFD62F97A),
//        @(0x8A65C9EC), @(0x14015C4F), @(0x63066CD9), @(0xFA0F3D63), @(0x8D080DF5),
//        @(0x3B6E20C8), @(0x4C69105E), @(0xD56041E4), @(0xA2677172), @(0x3C03E4D1),
//        @(0x4B04D447), @(0xD20D85FD), @(0xA50AB56B), @(0x35B5A8FA), @(0x42B2986C),
//        @(0xDBBBC9D6), @(0xACBCF940), @(0x32D86CE3), @(0x45DF5C75), @(0xDCD60DCF),
//        @(0xABD13D59), @(0x26D930AC), @(0x51DE003A), @(0xC8D75180), @(0xBFD06116),
//        @(0x21B4F4B5), @(0x56B3C423), @(0xCFBA9599), @(0xB8BDA50F), @(0x2802B89E),
//        @(0x5F058808), @(0xC60CD9B2), @(0xB10BE924), @(0x2F6F7C87), @(0x58684C11),
//        @(0xC1611DAB), @(0xB6662D3D), @(0x76DC4190), @(0x01DB7106), @(0x98D220BC),
//        @(0xEFD5102A), @(0x71B18589), @(0x06B6B51F), @(0x9FBFE4A5), @(0xE8B8D433),
//        @(0x7807C9A2), @(0x0F00F934), @(0x9609A88E), @(0xE10E9818), @(0x7F6A0DBB),
//        @(0x086D3D2D), @(0x91646C97), @(0xE6635C01), @(0x6B6B51F4), @(0x1C6C6162),
//        @(0x856530D8), @(0xF262004E), @(0x6C0695ED), @(0x1B01A57B), @(0x8208F4C1),
//        @(0xF50FC457), @(0x65B0D9C6), @(0x12B7E950), @(0x8BBEB8EA), @(0xFCB9887C),
//        @(0x62DD1DDF), @(0x15DA2D49), @(0x8CD37CF3), @(0xFBD44C65), @(0x4DB26158),
//        @(0x3AB551CE), @(0xA3BC0074), @(0xD4BB30E2), @(0x4ADFA541), @(0x3DD895D7),
//        @(0xA4D1C46D), @(0xD3D6F4FB), @(0x4369E96A), @(0x346ED9FC), @(0xAD678846),
//        @(0xDA60B8D0), @(0x44042D73), @(0x33031DE5), @(0xAA0A4C5F), @(0xDD0D7CC9),
//        @(0x5005713C), @(0x270241AA), @(0xBE0B1010), @(0xC90C2086), @(0x5768B525),
//        @(0x206F85B3), @(0xB966D409), @(0xCE61E49F), @(0x5EDEF90E), @(0x29D9C998),
//        @(0xB0D09822), @(0xC7D7A8B4), @(0x59B33D17), @(0x2EB40D81), @(0xB7BD5C3B),
//        @(0xC0BA6CAD), @(0xEDB88320), @(0x9ABFB3B6), @(0x03B6E20C), @(0x74B1D29A),
//        @(0xEAD54739), @(0x9DD277AF), @(0x04DB2615), @(0x73DC1683), @(0xE3630B12),
//        @(0x94643B84), @(0x0D6D6A3E), @(0x7A6A5AA8), @(0xE40ECF0B), @(0x9309FF9D),
//        @(0x0A00AE27), @(0x7D079EB1), @(0xF00F9344), @(0x8708A3D2), @(0x1E01F268),
//        @(0x6906C2FE), @(0xF762575D), @(0x806567CB), @(0x196C3671), @(0x6E6B06E7),
//        @(0xFED41B76), @(0x89D32BE0), @(0x10DA7A5A), @(0x67DD4ACC), @(0xF9B9DF6F),
//        @(0x8EBEEFF9), @(0x17B7BE43), @(0x60B08ED5), @(0xD6D6A3E8), @(0xA1D1937E),
//        @(0x38D8C2C4), @(0x4FDFF252), @(0xD1BB67F1), @(0xA6BC5767), @(0x3FB506DD),
//        @(0x48B2364B), @(0xD80D2BDA), @(0xAF0A1B4C), @(0x36034AF6), @(0x41047A60),
//        @(0xDF60EFC3), @(0xA867DF55), @(0x316E8EEF), @(0x4669BE79), @(0xCB61B38C),
//        @(0xBC66831A), @(0x256FD2A0), @(0x5268E236), @(0xCC0C7795), @(0xBB0B4703),
//        @(0x220216B9), @(0x5505262F), @(0xC5BA3BBE), @(0xB2BD0B28), @(0x2BB45A92),
//        @(0x5CB36A04), @(0xC2D7FFA7), @(0xB5D0CF31), @(0x2CD99E8B), @(0x5BDEAE1D),
//        @(0x9B64C2B0), @(0xEC63F226), @(0x756AA39C), @(0x026D930A), @(0x9C0906A9),
//        @(0xEB0E363F), @(0x72076785), @(0x05005713), @(0x95BF4A82), @(0xE2B87A14),
//        @(0x7BB12BAE), @(0x0CB61B38), @(0x92D28E9B), @(0xE5D5BE0D), @(0x7CDCEFB7),
//        @(0x0BDBDF21), @(0x86D3D2D4), @(0xF1D4E242), @(0x68DDB3F8), @(0x1FDA836E),
//        @(0x81BE16CD), @(0xF6B9265B), @(0x6FB077E1), @(0x18B74777), @(0x88085AE6),
//        @(0xFF0F6A70), @(0x66063BCA), @(0x11010B5C), @(0x8F659EFF), @(0xF862AE69),
//        @(0x616BFFD3), @(0x166CCF45), @(0xA00AE278), @(0xD70DD2EE), @(0x4E048354),
//        @(0x3903B3C2), @(0xA7672661), @(0xD06016F7), @(0x4969474D), @(0x3E6E77DB),
//        @(0xAED16A4A), @(0xD9D65ADC), @(0x40DF0B66), @(0x37D83BF0), @(0xA9BCAE53),
//        @(0xDEBB9EC5), @(0x47B2CF7F), @(0x30B5FFE9), @(0xBDBDF21C), @(0xCABAC28A),
//        @(0x53B39330), @(0x24B4A3A6), @(0xBAD03605), @(0xCDD70693), @(0x54DE5729),
//        @(0x23D967BF), @(0xB3667A2E), @(0xC4614AB8), @(0x5D681B02), @(0x2A6F2B94),
//        @(0xB40BBE37), @(0xC30C8EA1), @(0x5A05DF1B), @(0x2D02EF8D)
//    ];
//}

//- (NSInteger)getCrc_Calc:(Byte *)Context data:(NSData *)data{
//    int secretkey=0xFFFFFFFF;
//    return [self CRC32_Calculate:secretkey context:Context data:data] ^ secretkey;
//}

//- (NSInteger)CRC32_Calculate:(NSInteger)secretkey context: (Byte *)Context data:(NSData *)data{
//    NSArray *crctab =[self crc_tab];
//    NSInteger index;
//    for (int i = 0; i < data.length; i++) {
//        index = secretkey ^ Context[i];
//        
//        NSNumber *item = crctab[(index&0xff)];
//        NSInteger value = item.integerValue;
////        secretkey =  ((secretkey >> 8) ^ value);
//        
//        
//        secretkey =  ([[ARTSafeHelper new] asyncmethodWithValue:secretkey] ^ value);
//    }
//    NSLog(@"---sd-----%@",@(secretkey));
//    return secretkey;
//}

- (ARTWathDataAnalysis *)dataAnalysis{
    if (!_dataAnalysis) {
        ARTWathDataAnalysis *analysis = [[ARTWathDataAnalysis alloc]init];
        analysis.call_0x10_back = ^(ARTWathDataModel * _Nullable dataModel) {
            self.realDataModel = dataModel;
        };
        analysis.call_0x14_back = ^(NSData * _Nullable datas) {
            
        };
        analysis.call_0x1C_back = ^(NSData * _Nullable datas) {
            Byte *bytes = (Byte *)[datas bytes];
            ARTSingleShare.watchDevHisAllNumber = bytes[4];
            if(ARTSingleShare.watchDevHisAllNumber > 0){
                NSLog(@"有历史数据哈");
                self.showAlert = YES;
            }
        };
        analysis.call_0x1D_back = ^(NSData * _Nullable datas,BOOL complete) {
            if (complete) {
                // 同步时间
                [self.currentPeripheral writeValue:[ARTWathDataAnalysis syncTimestamp] forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithResponse];
                [self.currentPeripheral writeValue:[ARTWathDataAnalysis getDeviceHisAllCount] forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithResponse];
            }else{
                
                //
//                Byte temp[20] = {0xFE ,0x5A ,0x14 ,0x1D ,0x0C ,0x20 ,0xE6 ,0x47 ,0x45 ,0xCC ,0xF8 ,0xE2 ,0x92 ,0xF7 ,0xBC ,0xFB ,0xD4 ,0xA9 ,0x00 ,0x32};//;
//                datas = [NSData dataWithBytes:temp length:20];
                //
                
                Byte *data = (Byte *)[datas bytes];
                
                Byte crcche[4] = {};
                Byte sendcrcche[8] ={};
                
                crcche[0]=data[9];
                crcche[1]=data[8];
                crcche[2]=data[5];
                crcche[3]=data[4];
                NSInteger crc=[[ARTSafeHelper new] resultForAppWithValue:[NSData dataWithBytes:crcche length:4]];//[self getCrc_Calc:crcche data:[NSData dataWithBytes:crcche length:4]];//[[ARTSafeHelper new] intgetCrc_CalcWithContext:[NSData dataWithBytes:crcche length:4]];//;//(crcche);
                
                NSInteger crcn= [[ARTSafeHelper new] resultForDeviceWithValue:datas];//(data[13]&0xFF)<<24|(data[14]&0xFF)<<16|(data[17]&0xFF)<<8|data[18]&0xFF;
                if(crc==crcn){
//                    [QMUITips showWithText:@"相等了啊"];
                    sendcrcche[0]=data[13];
                    sendcrcche[1]=data[14];
                    sendcrcche[2]=data[17];
                    sendcrcche[3]=data[18];
                    sendcrcche[4]=data[4];
                    sendcrcche[5]=data[5];
                    sendcrcche[6]=data[8];
                    sendcrcche[7]=data[9];
                    NSInteger sendcrc=[[ARTSafeHelper new] resultForAppWithValue:[NSData dataWithBytes:sendcrcche length:8]];//CrcInfo.getCrc_Calc(sendcrcche);
                    
                    Byte check[] ={0xFE,0x5A,0x14,0x1D,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0};
//                    byte[] check = mSleepMainActivity.mSeelpComm.getShedcheck();
                    
//                    Random random=new Random();
                    check[4]= arc4random() % 255;
                    check[5]= arc4random() % 255;
                    check[6]= arc4random() % 255;
                    check[7]= arc4random() % 255;
                    check[8]= arc4random() % 255;
                    check[9]= arc4random() % 255;
                    check[10]= arc4random() % 255;
                    check[11]= arc4random() % 255;
                    check[12]= arc4random() % 255;
                    check[15]= arc4random() % 255;
                    check[16]= arc4random() % 255;
                    
                    check[13]= (sendcrc>>24&0xff);
                    check[14]= (sendcrc>>16&0xff);
                    check[17]= (sendcrc>>8&0xff);
                    check[18]= (sendcrc&0xff);
                    
                    NSLog(@"check写入=%@",[NSData dataWithBytes:check length:20]);
                    [self.currentPeripheral writeValue:[NSData dataWithBytes:check length:20] forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithResponse];
//                    mSleepMainActivity.artmonitor.writeDataCRC(check);
                }else {
//                    NSString *result = [NSString stringWithFormat:@"crc:%@,crcn:%@,data:%@",@(crc),@(crcn),[ASFHConverter convert_16String_with_16Data:datas]];
//                    [self lq_showAlertControllerWithMessage:result okHandle:^{
//                        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
//                        pasteboard.string = result;
//                        [QMUITips showInfo:@"内容已复制"];
//                    }];
//                    [QMUITips showWithText:@"不相等，断开啦"];
                    //断开
//                    mSleepMainActivity.artmonitor.disconnect();
//                    mSleepMainActivity.artmonitor.close();
                    [self.baby cancelAllPeripheralsConnection];
                    self.writeCharacteristic = nil;
                    self.notifyCharacteristic = nil;
                }
            }
        };
        _dataAnalysis = analysis;
    }
    return _dataAnalysis;
}

@end
